// 用于配置对应路由
let express = require('express')
let dormquery = require('../api/dorm_query')
let router = express.Router()
router.use(express.json());
router.use(express.urlencoded({
    extended: true
}));

// //获取所有宿舍信息
router.get('/', function (req, res) {
    res.redirect('/dorms'); // 重定向
});
router.get('/dorms', (req, res) => {
    dormquery.getall(function (rec) {
        res.json(rec).end();
    });
});

//获取指定name的宿舍信息 {通过id}
router.get('/dorms/:dorm_id', function (req, res) {
    var dorm_id = parseInt(req.params.dorm_id);
    dormquery.get(dorm_id, function (rec) {
        res.json(rec).end();
    });
    console.log(dorm_id);
});

//使用POST方法添加宿舍信息
router.post('/dorms', function (req, res) {
    var reqbody = req.body;
    console.log(reqbody);
    var arr = [];
    //遍历JSON数据中所有的值
    for (var key in reqbody) {
        arr.push(reqbody[key]);
    }
    dormquery.add([
        reqbody.bulid_name,
        reqbody.dorm_num,
        reqbody.head_name,
        reqbody.sex,
        reqbody.phone,
        reqbody.class_size,
        reqbody.real_number
    ], function (rec) {
        res.json(rec).end();
    });
});

//使用PUT方法修改楼层信息 TODO
router.put('/dorms/:dorm_id', function (req, res) {
    var dorm_id = parseInt(req.params.dorm_id);
    var reqbody = req.body;
    console.log(reqbody);
    //先判断ID是否有效，再执行修改操作
    dormquery.get(dorm_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的宿舍不存在！'
            });
        } else {
            var arr1 = [];
            var arr2 = [];
            for (var key in reqbody) {
                arr1.push(key); //键
                arr2.push(reqbody[key]); //值
            }
            dormquery.update([
                reqbody.dorm_num,
                reqbody.head_name,
                reqbody.sex,
                reqbody.phone,
                reqbody.class_size,
                reqbody.real_number,
                dorm_id
            ], function (rec) {
                res.json(rec).end();
            });
        }
    });
});

//使用DELETE方法删除图书信息
router.delete('/dorms/:id', function (req, res) {
    var dorm_id = parseInt(req.params.id);
    // var reqbody = req.body;
    //先判断ID是否有效，再执行删除操作
    dormquery.get(dorm_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的楼层不存在！'
            });
        } else {
            dormquery.del(dorm_id, function (p) {
                res.json(rec).end();
            });
        }
    });
});
module.exports = router